﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using Common.Logging;
using In.Api.Dto.HisWs;
using In.Api.Dto.Qy;
using Newtonsoft.Json;
using Qy.Yzrb.Dto.Data;
using Qy.Yzrb.Helpers;

namespace Qy.Yzrb.Controllers
{
    [AllowAnonymous]
    public class DataController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DataController));

        /// <summary>
        /// 获取院长日报统计数据
        /// </summary>
        /// <param name="timeRange">
        /// 时段：
        /// today - 昨日
        /// currentMonth - 本月
        /// <param name="day">自定义时间</param>
        [HttpGet]
        [ActionName("MzTotal")]
        public MzTotalResponse MzTotal(string timeRange,DateTime day)
        {
            //CookieHeaderValue cookie = Request.Headers.GetCookies("AzuDepartCookie").FirstOrDefault();
            bool showAmount = true;
            //if (cookie != null)
            //{
            //    //此处系统会自动UrlDecode
            //    var token = cookie["AzuDepartCookie"].Value;

            //    var depart = "";
            //    var isVerified = JwtTokenHelper.ValidateJwtToken(token, out depart);
            //    Logger.InfoFormat("isVerified:{0}", isVerified);
            //    if (isVerified)
            //    {
                    
            //        int[] departs = JsonConvert.DeserializeObject<int[]>(depart);
            //        if (departs.Contains(3))
            //        {
            //            showAmount = true;
            //        }
            //        Logger.InfoFormat("showAmount:{0}", showAmount);
            //    }
    
            //}

            var startDate = "";
            var endDate = "";
            DateTime yesterDay = DateTime.Today.AddDays(-1);
            if (day <= DateTime.Today)
            {
                yesterDay = day.AddDays(-1);
            }


            switch (timeRange)
            {
                case "today":
                    startDate = yesterDay.ToString("yyyy-MM-dd");
                    endDate = yesterDay.ToString("yyyy-MM-dd");
                    break;
                case "currentMonth":
                    startDate = yesterDay.StartOfMonth().ToString("yyyy-MM-dd");
                    endDate = yesterDay.ToString("yyyy-MM-dd");
                    break;
            }


            var request = new QyRequest();
            request.StartDate = startDate;
            request.EndDate = endDate;

            MzTotalResponse totalResponse = new MzTotalResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Total = "--",
                ContrastTotal = "--"
            };

            if (timeRange == "today")
            {
                //各科室门诊处方量
                GetOutpatientDeptPrescriptionNumberInfoResponse response;
                try
                {
                    var httpClient = InHttpClientHelper.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetOutpatientDeptPrescriptionNumberInfo", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<GetOutpatientDeptPrescriptionNumberInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取 院长日报-获取各科室门诊处方量统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new MzTotalResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取门诊日报信息超时"
                    };
                }
                if (response.ResultCode != "0")
                {
                    return new MzTotalResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }
                totalResponse.DeptOutpatients = new List<MzTotalResponse.OutPatient>();
                response.OutpatientDeptPrescriptionNumberInfos.ForEach(x =>
                {
                    totalResponse.DeptOutpatients.Add(new MzTotalResponse.OutPatient
                    {
                        DeptId = x.DeptId,
                        DeptName = x.DeptName,
                        Total = x.Total,
                        ContrastTotal = x.ContrastCount,
                        Unit = x.Unit
                    });
                });

            }
            else if (timeRange == "currentMonth")
            {
                DateTime _startDate = yesterDay.StartOfMonth();
                DateTime _endDate = yesterDay;
                totalResponse.DeptOutpatients = new List<MzTotalResponse.OutPatient>();
                List<MzTotalResponse.OutPatientInfo> lst = new List<MzTotalResponse.OutPatientInfo>();
                //循环获取总数
                //for (; _startDate <= _endDate; _startDate = _startDate.AddDays(1))
                //{
                    request.StartDate = _startDate.ToString("yyyy-MM-dd");
                    request.EndDate = _endDate.ToString("yyyy-MM-dd");
                    //各科室门诊处方量
                    GetOutpatientDeptPrescriptionNumberInfoResponse response;
                    try
                    {
                        var httpClient = InHttpClientHelper.GetClient();
                        var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetOutpatientDeptPrescriptionNumberInfo", request).Result;
                        responseMsg.EnsureSuccessStatusCode();
                        response = responseMsg.Content.ReadAsAsync<GetOutpatientDeptPrescriptionNumberInfoResponse>().Result;

                        if (response.ResultCode == "0")
                        {
                            response.OutpatientDeptPrescriptionNumberInfos.ForEach(x =>
                            {
                                lst.Add(new MzTotalResponse.OutPatientInfo
                                {
                                    DeptName = x.DeptName,
                                    Total = Convert.ToInt32(x.Total),
                                    ContrastTotal = Convert.ToInt32(x.ContrastCount),
                                });
                            });
                        }
                        //汇总
                        var q =
                        from p in lst
                        group p by p.DeptName into g
                        select new MzTotalResponse.OutPatientInfo
                        {
                            DeptName = g.Key,
                            Total = g.Sum(p => p.Total),
                            ContrastTotal = g.Sum(p => p.ContrastTotal),
                        };
                        totalResponse.DeptOutpatients = q.Select(x => new  MzTotalResponse.OutPatient
                        {
                            DeptName = x.DeptName,
                            Total = x.Total.ToString(),
                            ContrastTotal = x.ContrastTotal.ToString(),
                        }).ToList();
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("调用院内获取 院长日报-获取各科室门诊处方量统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                    }
//                }
          

                //门诊处方量
                GetOutpatientPrescriptionNumberResponse response1;
                request.StartDate = startDate;
                request.EndDate = endDate;
                try
                {
                    var httpClient = InHttpClientHelper.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetOutpatientPrescriptionNumber", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response1 = responseMsg.Content.ReadAsAsync<GetOutpatientPrescriptionNumberResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取 院长日报-获取门诊处方量 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new MzTotalResponse
                    {
                        ResultCode = "4",
                        ResultMsg = "获取门诊日报信息超时"
                    };
                }
                if (response1.ResultCode != "0")
                {
                    return new MzTotalResponse
                    {
                        ResultCode = "5",
                        ResultMsg = response1.ResultDesc
                    };
                }

                totalResponse.VisitNum = response1.Total;
                totalResponse.ContrastVisitNum = response1.ContrastCount;
                totalResponse.TotalUnit = response1.Unit;

                if (showAmount)
                {

                    request.StartDate = yesterDay.ToString("yyyy-MM-dd");
                    request.EndDate = yesterDay.ToString("yyyy-MM-dd");
                    //获取门诊收入
                    GetOutpatientIncomeResponse response2;
                    try
                    {
                        var httpClient = InHttpClientHelper.GetClient();
                        var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetOutpatientIncome", request).Result;
                        responseMsg.EnsureSuccessStatusCode();
                        response2 = responseMsg.Content.ReadAsAsync<GetOutpatientIncomeResponse>().Result;
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("调用院内获取 院长日报-获取门诊收入 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                        return new MzTotalResponse
                        {
                            ResultCode = "6",
                            ResultMsg = "获取门诊日报信息超时"
                        };
                    }
                    if (response2.ResultCode != "0")
                    {
                        return new MzTotalResponse
                        {
                            ResultCode = "6",
                            ResultMsg = response2.ResultDesc
                        };
                    }

                    totalResponse.Total = response2.Total;
                    totalResponse.ContrastTotal = response2.ContrastCount;
                    totalResponse.Unit = response2.Unit;
                }

            }

            return totalResponse;
        }

        /// <summary>
        /// 获取院长日报统计数据
        /// </summary>
        /// <param name="timeRange">
        /// 时段：
        /// today - 昨日
        /// currentMonth - 本月
        /// </param>
        /// <param name="day">自定义时间</param>
        [HttpGet]
        [ActionName("ZyTotal")]
        public ZyTotalResponse ZyTotal(string timeRange,DateTime day)
        {
            //CookieHeaderValue cookie = Request.Headers.GetCookies("AzuDepartCookie").FirstOrDefault();
            bool showAmount = true;
            //if (cookie != null)
            //{
            //    //此处系统会自动UrlDecode
            //    var token = cookie["AzuDepartCookie"].Value;

            //    var depart = "";
            //    var isVerified = JwtTokenHelper.ValidateJwtToken(token, out depart);
            //    Logger.InfoFormat("isVerified:{0}", isVerified);
            //    if (isVerified)
            //    {

            //        int[] departs = JsonConvert.DeserializeObject<int[]>(depart);
            //        if (departs.Contains(3))
            //        {
            //            showAmount = true;
            //        }
            //        Logger.InfoFormat("showAmount:{0}", showAmount);
            //    }

            //}

            var startDate = "";
            var endDate = "";

            DateTime yesterDay = DateTime.Today.AddDays(-1);
            if (day <= DateTime.Today)
            {
                yesterDay = day.AddDays(-1);
            }

            switch (timeRange)
            {
                case "today":
                    startDate = yesterDay.ToString("yyyy-MM-dd");
                    endDate = yesterDay.ToString("yyyy-MM-dd");
                    break;
                case "currentMonth":
                    startDate = yesterDay.StartOfMonth().ToString("yyyy-MM-dd");
                    endDate = yesterDay.ToString("yyyy-MM-dd");
                    break;
            }


            var request = new QyRequest();
            request.StartDate = startDate;
            request.EndDate = endDate;

            ZyTotalResponse totalResponse = new ZyTotalResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Total = "--",
                ContrastTotal = "--"
            };
            if (timeRange == "today")
            {
                //现住院人数
                GetInpatientDeptNumberInfoResponse response;
                try
                {
                    var httpClient = InHttpClientHelper.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetInpatientDeptNumberInfo", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<GetInpatientDeptNumberInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取 院长日报-获取各科室现有住院人数统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new ZyTotalResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取院长日报信息超时"
                    };
                }
                if (response.ResultCode != "0")
                {
                    return new ZyTotalResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }
                totalResponse.DeptInpatients = new List<ZyTotalResponse.InPatientNum>();
                response.InpatientDeptNumbers.ForEach(x =>
                {
                    totalResponse.DeptInpatients.Add(new ZyTotalResponse.InPatientNum
                    {
                        DeptId = x.DeptId,
                        DeptName = x.DeptName,
                        Total = x.Total,
                        ContrastTotal = x.ContrastCount
                    });
                });

            }
            else if (timeRange == "currentMonth")
            {
                //获取入院总人数
                GetInpatientTotalNumberResponse response1;
                try
                {
                    var httpClient = InHttpClientHelper.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetInpatientTotalNumber", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response1 = responseMsg.Content.ReadAsAsync<GetInpatientTotalNumberResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取 院长日报-获取入院总人数 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new ZyTotalResponse
                    {
                        ResultCode = "4",
                        ResultMsg = "获取院长日报信息超时"
                    };
                }
                if (response1.ResultCode != "0")
                {
                    return new ZyTotalResponse
                    {
                        ResultCode = "5",
                        ResultMsg = response1.ResultDesc
                    };
                }

                totalResponse.VisitNum = response1.Total;
                totalResponse.ContrastVisitNum = response1.ContrastCount;

                //当月现住院人数明细
                GetInpatientDeptNumberInfoResponse response;
                try
                {
                    var httpClient = InHttpClientHelper.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetInpatientDeptInNumberInfo", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<GetInpatientDeptNumberInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取 院长日报-获取各科室现有住院人数明细统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new ZyTotalResponse
                    {
                        ResultCode = "2",

                        ResultMsg = "获取院长日报信息超时"
                    };
                }
                if (response.ResultCode != "0")
                {
                    return new ZyTotalResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }
                totalResponse.DeptInpatients = new List<ZyTotalResponse.InPatientNum>();
                response.InpatientDeptNumbers.ForEach(x =>
                {
                    totalResponse.DeptInpatients.Add(new ZyTotalResponse.InPatientNum
                    {
                        DeptId = x.DeptId,
                        DeptName = x.DeptName,
                        Total = x.Total,
                        ContrastTotal = x.ContrastCount
                    });
                });

                if (showAmount)
                {
                    request.StartDate = yesterDay.ToString("yyyy-MM-dd");
                    request.EndDate = yesterDay.ToString("yyyy-MM-dd");

                    //获取住院收入
                    GetInpatientIncomeResponse response2;
                    try
                    {
                        var httpClient = InHttpClientHelper.GetClient();
                        var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetInpatientIncome", request).Result;
                        responseMsg.EnsureSuccessStatusCode();
                        response2 = responseMsg.Content.ReadAsAsync<GetInpatientIncomeResponse>().Result;
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("调用院内获取 院长日报-获取住院收入 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                        return new ZyTotalResponse
                        {
                            ResultCode = "6",
                            ResultMsg = "获取院长日报信息超时"
                        };
                    }
                    if (response2.ResultCode != "0")
                    {
                        return new ZyTotalResponse
                        {
                            ResultCode = "6",
                            ResultMsg = response2.ResultDesc
                        };
                    }

                    totalResponse.Total = response2.Total;
                    totalResponse.ContrastTotal = response2.ContrastCount;
                    totalResponse.Unit = response2.Unit;
                }

            }

            return totalResponse;
        }

        [HttpGet]
        [ActionName("GetDepartList")]
        public GetDepartListResponse GetDepartList()
        {
            GetDepartListResponse departResponse = new GetDepartListResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };
            string requestDay = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            var request = new QyRequest();
            request.StartDate = requestDay;
            request.EndDate = requestDay;

            GetInpatientDeptNumberInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetInpatientDeptNumberInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetInpatientDeptNumberInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取各科室现有住院人数统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetDepartListResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new GetDepartListResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            departResponse.InpatientList = new List<GetDepartListResponse.Depart>();
            response.InpatientDeptNumbers.ForEach(x =>
            {
                departResponse.InpatientList.Add(new GetDepartListResponse.Depart
                {
                    DeptId = x.DeptId,
                    DeptName = x.DeptName
                });
            });


            GetOutpatientDeptPrescriptionNumberInfoResponse outResponse;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetOutpatientDeptPrescriptionNumberInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                outResponse = responseMsg.Content.ReadAsAsync<GetOutpatientDeptPrescriptionNumberInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取各科室门诊处方量统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetDepartListResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取门诊日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new GetDepartListResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }
            departResponse.OutpatientList = new List<GetDepartListResponse.Depart>();
            outResponse.OutpatientDeptPrescriptionNumberInfos.ForEach(x =>
            {
                departResponse.OutpatientList.Add(new GetDepartListResponse.Depart
                {
                    DeptId = x.DeptId,
                    DeptName = x.DeptName
                });
            });

            return departResponse;
        }

        [HttpGet]
        [ActionName("MzLineTotal")]
        public MzLineTotalResponse MzLineTotal(string startDay,string endDay,string deptId,string type)
        {
            var request = new QyRequest();
            request.StartDate = startDay;
            request.EndDate = endDay;
            request.DeptId = deptId;

            MzLineTotalResponse totalResponse = new MzLineTotalResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };
            //各科室门诊处方量
            GetOutpatientDeptPrescriptionNumberInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetOutpatientDeptPrescriptionNumberInfoByDept", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetOutpatientDeptPrescriptionNumberInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取各科室门诊处方量统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new MzLineTotalResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取门诊日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new MzLineTotalResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.DeptOutpatients = new List<MzLineTotalResponse.OutPatient>();
            List<MzLineTotalResponse.OutPatient> list = new List<MzLineTotalResponse.OutPatient>();
            if (type == "0")
            {
                //按日统计
                response.OutpatientDeptPrescriptionNumberInfos.OrderBy(x =>x.Date).ForEach(x =>
                {
                    totalResponse.DeptOutpatients.Add(new MzLineTotalResponse.OutPatient
                    {
                        Total = Convert.ToInt32(x.Total),
                        ContrastTotal = Convert.ToInt32(x.ContrastCount),
                        Date = x.Date
                    });
                });
            }
            else if(type == "1")
            {
                //按月/年统计
                response.OutpatientDeptPrescriptionNumberInfos.OrderBy(x => x.Date.Substring(0, 7)).ForEach(x =>
                   {
                       list.Add(new MzLineTotalResponse.OutPatient
                       {
                           Total = Convert.ToInt32(x.Total),
                           ContrastTotal = Convert.ToInt32(x.ContrastCount),
                           Date = x.Date.Substring(0, 7)
                       });
                   });

                //汇总
                var q =
                from p in list
                group p by p.Date into g
                select new MzLineTotalResponse.OutPatient
                {
                    Date = g.Key,
                    Total = g.Sum(p => p.Total),
                    ContrastTotal = g.Sum(p => p.ContrastTotal),
                };
                totalResponse.DeptOutpatients = q.OrderBy(x => x.Date).Select(x => new MzLineTotalResponse.OutPatient
                {
                    Date = x.Date,
                    Total = x.Total,
                    ContrastTotal = x.ContrastTotal
                }).ToList();

            }


            return totalResponse;
        }

        [HttpGet]
        [ActionName("ZyLineTotal")]
        public ZyLineTotalResponse ZyLineTotal(string startDay, string endDay, string deptId, string type)
        {
            var request = new QyRequest();
            request.StartDate = startDay;
            request.EndDate = endDay;
            request.DeptId = deptId;

            ZyLineTotalResponse totalResponse = new ZyLineTotalResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            GetInpatientDeptNumberInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetInpatientDeptNumberInfoByDept", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetInpatientDeptNumberInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取各科室现有住院人数统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new ZyLineTotalResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new ZyLineTotalResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }


            totalResponse.DeptInpatients = new List<ZyLineTotalResponse.InPatientNum>();
            List<ZyLineTotalResponse.InPatientNum> list = new List<ZyLineTotalResponse.InPatientNum>();
            if (type == "0")
            {
                //按日统计
                response.InpatientDeptNumbers.OrderBy(x => 
                            x.Date).ForEach(x =>
                {
                    totalResponse.DeptInpatients.Add(new ZyLineTotalResponse.InPatientNum
                    {
                        Total = Convert.ToInt32(x.Total),
                        ContrastTotal = Convert.ToInt32(x.ContrastCount),
                        Date = x.Date
                    });
                });
            }
            else if (type == "1")
            {
                //按月/年统计
                response.InpatientDeptNumbers.OrderBy(x =>
                            x.Date.Substring(0, 7)).ForEach(x =>
                {
                    list.Add(new ZyLineTotalResponse.InPatientNum
                    {
                        Total = Convert.ToInt32(x.Total),
                        ContrastTotal = Convert.ToInt32(x.ContrastCount),
                        Date = x.Date.Substring(0, 7)
                    });
                });
                    
                //汇总
                var q =
                from p in list
                group p by p.Date into g
                select new MzLineTotalResponse.OutPatient
                {
                    Date = g.Key,
                    Total = g.Sum(p => p.Total),
                    ContrastTotal = g.Sum(p => p.ContrastTotal)
                };
                totalResponse.DeptInpatients = q.OrderBy(x => x.Date).OrderBy(x =>
                              x.Date).Select(x => new ZyLineTotalResponse.InPatientNum
                              {
                                  Date = x.Date,
                                  Total = x.Total,
                                  ContrastTotal = x.ContrastTotal
                              }).ToList();

            }

            return totalResponse;
        }


        /// <summary>
        /// 获取自助终端使用情况信息
        /// </summary>
        /// <param name="day">自定义时间</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SelfServiceTerminalTotal")]
        public SelfServiceTerminalResponse SelfServiceTerminalTotal(DateTime day)
        {
            var startDate = "";
            var endDate = "";
            DateTime yesterDay = DateTime.Today.AddDays(-1);
            if (day <= DateTime.Today)
            {
                yesterDay = day.AddDays(-1);
            }

            startDate = yesterDay.ToString("yyyy-MM-dd");
            endDate = yesterDay.ToString("yyyy-MM-dd");

            QyRequest request = new QyRequest();
            request.StartDate = startDate;
            request.EndDate = endDate;


            SelfServiceTerminalResponse  totalResponse = new SelfServiceTerminalResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取入院总人数
            GetSelfServiceTerminalInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetSelfServiceTerminalInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetSelfServiceTerminalInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-自助终端使用情况 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new SelfServiceTerminalResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new SelfServiceTerminalResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.RegCount = response.RegCount;
            totalResponse.ClinPayCount = response.ClinPayCount;
            totalResponse.Unit = response.Unit;
            totalResponse.TotalMoney = response.TotalMoney;

            return totalResponse;
        }

        /// <summary>
        /// 获取微信汇总
        /// </summary>
        /// <param name="day">自定义时间</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetWeixinInfo")]
        public WeixinInfoResponse GetWeixinInfo(DateTime day)
        {
            var startDate = "";
            var endDate = "";
            DateTime yesterDay = DateTime.Today.AddDays(-1);
            if (day <= DateTime.Today)
            {
                yesterDay = day.AddDays(-1);
            }

            startDate = yesterDay.ToString("yyyy-MM-dd");
            endDate = yesterDay.ToString("yyyy-MM-dd");

            QyRequest request = new QyRequest();
            request.StartDate = startDate;
            request.EndDate = endDate;


            WeixinInfoResponse totalResponse = new WeixinInfoResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取入院总人数
            GetWeixinInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetWeixinInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetWeixinInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-自助终端使用情况 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new WeixinInfoResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new WeixinInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.RegCount = response.RegCount;
            totalResponse.ClinPayCount = response.ClinPayCount;
            totalResponse.WardDepositCount = response.WardDepositCount;
            totalResponse.TotalMoney = response.TotalMoney;

            return totalResponse;
        }

        /// <summary>
        /// 实时统计门诊各科各上班医生当前候诊人数
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOutPatientWaitingInfo")]
        public OutPatientWaitingInfoResponse GetOutPatientWaitingInfo()
        {
            QyRequest request = new QyRequest();


            OutPatientWaitingInfoResponse totalResponse = new OutPatientWaitingInfoResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取入院总人数
            GetOutPatientWaitingInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetOutPatientWaitingInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetOutPatientWaitingInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-门诊各科各上班医生当前候诊人数 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new OutPatientWaitingInfoResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new OutPatientWaitingInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.OutPatientWaitingInfoes = new List<OutPatientWaitingInfoResponse.OutPatientWaitingInfo>();

            response.OutPatientWaitingInfoes.ForEach(x =>
            {
                totalResponse.OutPatientWaitingInfoes.Add(new OutPatientWaitingInfoResponse.OutPatientWaitingInfo
                {
                    DeptName = x.DeptName,
                    DoctName = x.DoctName,
                    WaitingCount = Convert.ToInt32(x.WaitingCount) 
                });
            });
            if (totalResponse.OutPatientWaitingInfoes.Any())
            {

                int maxCount = totalResponse.OutPatientWaitingInfoes.Max(x => x.WaitingCount);
                totalResponse.OutPatientWaitingInfoes.ForEach(x =>
                {
                    x.Percent = maxCount == 0 ? 0 : x.WaitingCount*100/maxCount;
                });
            }
            return totalResponse;
        }

        /// <summary>
        /// 实时统计门诊各科各上班医生当前候诊人数
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetTreatmentWaitingInfo")]
        public TreatmentWaitingInfoResponse GetTreatmentWaitingInfo()
        {
            QyRequest request = new QyRequest();


            TreatmentWaitingInfoResponse totalResponse = new TreatmentWaitingInfoResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取入院总人数
            GetTreatmentWaitingInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetTreatmentWaitingInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetTreatmentWaitingInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-治疗区当前排队人数 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new TreatmentWaitingInfoResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new TreatmentWaitingInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.TreatmentWaitingInfoes = new List<TreatmentWaitingInfoResponse.TreatmentWaitingInfo>();

            response.TreatmentWaitingInfoes.ForEach(x =>
            {
                totalResponse.TreatmentWaitingInfoes.Add(new TreatmentWaitingInfoResponse.TreatmentWaitingInfo
                {
                    TreatName = x.TreatName,
                    WaitingCount = Convert.ToInt32(x.WaitingCount)
                });
            });
            if (totalResponse.TreatmentWaitingInfoes.Any())
            {
                int maxCount = totalResponse.TreatmentWaitingInfoes.Max(x => x.WaitingCount);
                totalResponse.TreatmentWaitingInfoes.ForEach(x =>
                {
                    x.Percent = maxCount == 0 ? 0 : x.WaitingCount*100/maxCount;
                });
            }
            return totalResponse;
        }

        /// <summary>
        /// 实时统计门诊各科各上班医生当前候诊人数
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("BscanWaitingInfo")]
        public TreatmentWaitingInfoResponse BscanWaitingInfo()
        {
            QyRequest request = new QyRequest();


            TreatmentWaitingInfoResponse totalResponse = new TreatmentWaitingInfoResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取入院总人数
            BscanWaitingInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/BscanWaitingInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<BscanWaitingInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-治疗区当前排队人数 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new TreatmentWaitingInfoResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new TreatmentWaitingInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.TreatmentWaitingInfoes = new List<TreatmentWaitingInfoResponse.TreatmentWaitingInfo>();

            response.BscanWaitingInfoes.ForEach(x =>
            {
                totalResponse.TreatmentWaitingInfoes.Add(new TreatmentWaitingInfoResponse.TreatmentWaitingInfo
                {
                    TreatName = x.QueueName,
                    WaitingCount = Convert.ToInt32(x.WaitingCount)
                });
            });
            if (totalResponse.TreatmentWaitingInfoes.Any())
            {
                int maxCount = totalResponse.TreatmentWaitingInfoes.Max(x => x.WaitingCount);
                totalResponse.TreatmentWaitingInfoes.ForEach(x =>
                {
                    x.Percent = maxCount == 0 ? 0 : x.WaitingCount * 100 / maxCount;
                });
            }
            return totalResponse;
        }


        /// <summary>
        /// 获取实时各科总床位及使用情况
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetBedUsedDetailInfo")]
        public BedUsedInfoResponse GetBedUsedDetailInfo()
        {
            QyRequest request = new QyRequest();


            BedUsedInfoResponse totalResponse = new BedUsedInfoResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取实时各科总床位及使用情况
            GetBedUsedDetailInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetBedUsedDetailInfo ", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetBedUsedDetailInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取实时各科总床位及使用情况 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new BedUsedInfoResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new BedUsedInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.Beds = new List<BedUsedInfoResponse.BedInfo>();

            response.Beds.ForEach(x =>
            {
                totalResponse.Beds.Add(new BedUsedInfoResponse.BedInfo
                {
                    DeptId = x.DeptId,
                    DeptName = x.DeptName,
                    UsedBed = x.UsedBed,
                    TotalBed = x.TotalBed,
                    Percent = x.Percent
                });
            });

            return totalResponse;
        }


        /// <summary>
        /// 获取医城通终端使用情况信息
        /// </summary>
        /// <param name="day">自定义时间</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetYCTTerminalInfo")]
        public YCTTerminalInfoResponse GetYCTTerminalInfo(DateTime day)
        {
            var startDate = "";
            var endDate = "";
            DateTime yesterDay = DateTime.Today.AddDays(-1);
            if (day <= DateTime.Today)
            {
                yesterDay = day.AddDays(-1);
            }

            startDate = yesterDay.ToString("yyyy-MM-dd");
            endDate = yesterDay.ToString("yyyy-MM-dd");

            QyRequest request = new QyRequest();
            request.StartDate = startDate;
            request.EndDate = endDate;


            YCTTerminalInfoResponse totalResponse = new YCTTerminalInfoResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取入院总人数
            GetYCTTerminalInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetYCTTerminalInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetYCTTerminalInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取医城通终端使用情况信息 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new YCTTerminalInfoResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new YCTTerminalInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.RegCount = response.RegCount;
            totalResponse.ClinPayCount = response.ClinPayCount;
            totalResponse.TotalMoney = response.TotalMoney;
            totalResponse.Unit = response.Unit;

            return totalResponse;
        }


        /// <summary>
        /// 获取支付宝使用情况信息
        /// </summary>
        /// <param name="day">自定义时间</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAlipayTerminalInfo")]
        public AlipayTerminalInfoResponse GetAlipayTerminalInfo(DateTime day)
        {
            var startDate = "";
            var endDate = "";
            DateTime yesterDay = DateTime.Today.AddDays(-1);
            if (day <= DateTime.Today)
            {
                yesterDay = day.AddDays(-1);
            }

            startDate = yesterDay.ToString("yyyy-MM-dd");
            endDate = yesterDay.ToString("yyyy-MM-dd");

            QyRequest request = new QyRequest();
            request.StartDate = startDate;
            request.EndDate = endDate;


            AlipayTerminalInfoResponse totalResponse = new AlipayTerminalInfoResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };

            //获取入院总人数
            GetAlipayTerminalInfoResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetAlipayTerminalInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetAlipayTerminalInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取支付宝使用情况信息 统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new AlipayTerminalInfoResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院长日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new AlipayTerminalInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.RegCount = response.RegCount;
            totalResponse.ClinPayCount = response.ClinPayCount;
            totalResponse.TotalMoney = response.TotalMoney;
            totalResponse.Unit = response.Unit;

            return totalResponse;
        }


        /// <summary>
        /// 获取各科室门诊处方量统计信息
        /// </summary>
        /// <param name="startDay">开始时间</param>
        /// <param name="endDay">结束时间</param>
        /// <param name="deptId">科室Id</param>
        /// <param name="type">统计类型</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("MzBookingPercent")]
        public MzBookingLineTotalResponse MzBookingPercent(string startDay, string endDay, string deptId, string type)
        {
            var request = new QyRequest();
            request.StartDate = startDay;
            request.EndDate = endDay;
            request.DeptId = deptId;

            MzBookingLineTotalResponse totalResponse = new MzBookingLineTotalResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };
            //各科室门诊处方量
            GetBookingPercentResponse response;
            try
            {
                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetBookingPercent", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetBookingPercentResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取各科室门诊处方量统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new MzBookingLineTotalResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取门诊日报信息超时"
                };
            }
            if (response.ResultCode != "0")
            {
                return new MzBookingLineTotalResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            //去年各科室门诊处方量
            GetBookingPercentResponse constractResponse;
            try
            {
                //计算同期数值
                request.StartDate = Convert.ToDateTime(startDay).AddYears(-1).ToString("yyyy-MM-dd");
                request.EndDate = Convert.ToDateTime(endDay).AddYears(-1).ToString("yyyy-MM-dd");
                request.DeptId = deptId;


                var httpClient = InHttpClientHelper.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("QyWs/GetBookingPercent", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                constractResponse = responseMsg.Content.ReadAsAsync<GetBookingPercentResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取 院长日报-获取各科室门诊处方量统计信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new MzBookingLineTotalResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取门诊日报信息超时"
                };
            }
            if (constractResponse.ResultCode != "0")
            {
                return new MzBookingLineTotalResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            totalResponse.DeptOutpatients = new List<MzBookingLineTotalResponse.OutPatient>();
            List<MzBookingLineTotalResponse.OutPatientTotal> list = new List<MzBookingLineTotalResponse.OutPatientTotal>();
            List<MzBookingLineTotalResponse.OutPatientLocal> localList = new List<MzBookingLineTotalResponse.OutPatientLocal>();
            response.BookingPercentInfoes.ForEach(x =>
            {
                var contrastEntity =
                    constractResponse.BookingPercentInfoes.FirstOrDefault(
                        y => Convert.ToDateTime(x.Date) == Convert.ToDateTime(y.Date).AddYears(1));
                localList.Add(new MzBookingLineTotalResponse.OutPatientLocal
                {
                    Total = x.RegNum,
                    WxRegNum = x.WxRegNum,
                    BookingNum = x.BookingNum,
                    Date = x.Date.Replace('/','-'),
                    Percent = x.Percent,
                    ContrastTotal = contrastEntity?.RegNum ?? "0",
                    ContrastBookingNum = contrastEntity?.BookingNum ?? "0",
                    ContrastWxRegNum = contrastEntity?.WxRegNum ?? "0",
                    ContrastPercent = contrastEntity?.Percent ?? "0",
                });
            });


            if (type == "0")
            {
                //按日统计
                localList.OrderBy(x =>
                            x.Date).ForEach(x =>
                {
                    totalResponse.DeptOutpatients.Add(new MzBookingLineTotalResponse.OutPatient
                    {
                        Percent = string.IsNullOrEmpty(x.Percent) ? 0:  Convert.ToDecimal(x.Percent.Replace("%","") ),
                        Date = string.IsNullOrEmpty(x.Date) ? "" : x.Date.Replace(" 0:00:00", ""),
                        ContrastPercent = string.IsNullOrEmpty(x.ContrastPercent) ? 0 : Convert.ToDecimal(x.ContrastPercent.Replace("%", ""))
                    });
                });
            }
            else if (type == "1")
            {
                //按月/年统计
                localList.OrderBy(x =>
                            x.Date.Substring(0, 7)).ForEach(x =>
                {
                    list.Add(new MzBookingLineTotalResponse.OutPatientTotal
                    {
                        Total = Convert.ToInt32(x.Total),
                        RegNum = Convert.ToInt32(x.BookingNum) + Convert.ToInt32(x.WxRegNum),
                        Date = x.Date.Substring(0, 7),
                        ContrastTotal = Convert.ToInt32(x.ContrastTotal),
                        ContrastRegNum = Convert.ToInt32(x.ContrastBookingNum) + Convert.ToInt32(x.ContrastWxRegNum),
                    });
                });

                //汇总
                var q =
                from p in list
                group p by p.Date into g
                select new MzBookingLineTotalResponse.OutPatientTotal
                {
                    Date = g.Key,
                    Total = g.Sum(p => p.Total),
                    RegNum = g.Sum(p => p.RegNum),
                    ContrastTotal = g.Sum(p => p.ContrastTotal),
                    ContrastRegNum = g.Sum(p => p.ContrastRegNum),
                };
                totalResponse.DeptOutpatients = q.OrderBy(x =>
                            x.Date).Select(x => new MzBookingLineTotalResponse.OutPatient
                {
                    Date = x.Date,
                    Percent = x.Total == 0 ? 0.00m : Math.Round( x.RegNum * 100m / x.Total ,2),
                    ContrastPercent = x.ContrastTotal == 0 ? 0.00m : Math.Round(x.ContrastRegNum * 100m / x.ContrastTotal, 2),
                }).ToList();
            }


            return totalResponse;
        }
    }
}
